#pragma once
#include <iostream>
#include "Log.hpp"
#include "Thread.hpp"
#include "LockGuard.hpp"
#include <vector>
#include <queue>

static const int tdefault_num = 5;

template <class T>
class threadpool
{
public:
    static threadpool<T> *GetInstance()
    {
        if (_tp == nullptr)
        {
            LockGuard lockguard(&_sig_mutex);
            if (_tp == nullptr)
            {
                LOG(INFO, "create threadpool.\n");
                _tp = new threadpool();
                _tp->Init();
                _tp->Start();
            }
            else
            {
                LOG(INFO, "get threadpool.\n");
            }
        }

        return _tp;
    }

    void Stop()
    {
        LockQueue();
        _isrunning = false;
        WakeAll();
        UnlockQueue();
        LOG(INFO, "Thread Pool Stop Success!\n");
    }

    void Equeue(const T &in)
    {
        LockQueue();
        if (_isrunning)
        {
            _task_queue.push(in);
            if (_sleep_thread_num > 0)
                WakeUp();
        }
        UnlockQueue();
    }

    ~threadpool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    threadpool(int thread_mum = tdefault_num) : _thread_num(thread_mum), _isrunning(false), _sleep_thread_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void Start()
    {
        _isrunning = true;
        for (auto &thread : _threads)
        {

            LOG(DEBUG, "start thread %s done.\n", thread.Name().c_str());
            thread.Start();
        }
    }

    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }

    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }

    void WakeAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool isEmpty()
    {
        return _task_queue.empty();
    }

    void HandlerTask(const std::string &name)
    {
        while (true)
        {
            LockQueue();                    // 获取锁
            while (isEmpty() && _isrunning) // 线程池运行一段时间后，任务队列为空则线程池闲置线程集体休眠
            {
                _sleep_thread_num++;
                LOG(INFO, "%s thread sleep begin!\n", name.c_str());
                Sleep();
                LOG(INFO, "%s thread wake up!\n", name.c_str());
                _sleep_thread_num--;
            }

            while (isEmpty() && !_isrunning) // 判断没有任务且线程池没有在运行的情况
            {
                UnlockQueue();
                LOG(INFO, "%s thread quit\n", name.c_str());
            }

            T t = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();
            t(); // 处理任务，此次不能在临界区处理

            //LOG(DEBUG, "hander task done.task is:%s\n", t.result().c_str());
        }
    }

    void Init()
    {
        func_t func = std::bind(&threadpool::HandlerTask, this, std::placeholders::_1);
        for (int i = 0; i < _thread_num; i++)
        {
            std::string threadname = "thread-" + std::to_string(i + 1); // 为线程编号
            _threads.emplace_back(threadname, func);                    // 将线程名及其回调的函数插入
            LOG(DEBUG, "construct thread %s done, init success\n", threadname.c_str());
        }
    }

    threadpool(const threadpool<T> &) = delete;
    void operator=(const threadpool<T> &) = delete;

private:
    std::vector<Thread> _threads;
    int _thread_num;
    std::queue<T> _task_queue;
    bool _isrunning;
    int _sleep_thread_num;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例模式
    static threadpool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

template <typename T>
threadpool<T> *threadpool<T>::_tp = nullptr;

template <typename T>
pthread_mutex_t threadpool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;